<template>
	<view class="position-container">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 导航栏 -->
		<view class="navbar">
			<view class="navbar-left" @click="goBack">
				<u-icon name="arrow-left" size="40" color="#333"></u-icon>
			</view>
			<view class="navbar-center">
				<view class="search-box">
					<u-icon name="search" size="32" color="#999" class="search-icon"></u-icon>
					<input 
						class="search-input" 
						type="text" 
						placeholder="搜索目的地" 
						v-model="searchKeyword"
						@input="onSearchInput"
						@confirm="onSearchConfirm"
						:focus="searchFocus"
					/>
				</view>
			</view>
			<view class="navbar-right">
				<view class="search-btn" @click="onSearchConfirm">搜索</view>
			</view>
		</view>
		
		<!-- 内容区域 -->
		<scroll-view 
			class="content-scroll" 
			scroll-y 
			:scroll-into-view="scrollIntoView"
			:scroll-with-animation="true"
			@scroll="onScroll"
		>
			<!-- 当前位置 -->
			<view class="section">
				<view class="section-title">当前位置</view>
				<view class="city-tags">
					<view class="city-tag current" @click="selectCity(currentCity)">
						<u-icon name="map-pin" size="28" color="#3c9cff"></u-icon>
						<text>{{ currentCity }}</text>
					</view>
				</view>
			</view>
			
			<!-- 经常访问 -->
			<view class="section" v-if="frequentCities.length > 0">
				<view class="section-title">经常访问</view>
				<view class="city-tags">
					<view 
						class="city-tag" 
						v-for="(city, index) in frequentCities" 
						:key="index"
						@click="selectCity(city.regionName)"
					>
						{{ city.regionName }}
					</view>
				</view>
			</view>
			
			<!-- 搜索结果 -->
			<view class="section" v-if="showSearchResult">
				<view class="section-title">搜索结果</view>
				<view class="city-tags">
					<view 
						class="city-tag" 
						v-for="(city, index) in searchResult" 
						:key="index"
						@click="selectCity(city.regionName)"
					>
						{{ city.regionName }}
					</view>
				</view>
			</view>
			
			<!-- 城市列表（按字母分组） -->
			<view class="section" v-if="!showSearchResult">
				<view 
					class="letter-section" 
					v-for="(cities, letter) in cityGroups" 
					:id="'letter-' + letter"
					:key="letter"
				>
					<view class="letter-title">{{ letter }}</view>
					<view class="city-tags">
						<view 
							class="city-tag" 
							v-for="(city, index) in cities" 
							:key="city.id || index"
							@click="selectCity(city.regionName)"
						>
							{{ city.regionName }}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 字母索引 -->
		<view 
			class="letter-index" 
			v-if="!showSearchResult && letterList.length > 0"
			@touchstart="onLetterIndexTouchStart"
			@touchmove="onLetterIndexTouchMove"
			@touchend="onLetterIndexTouchEnd"
		>
			<view 
				class="letter-item" 
				v-for="letter in letterList" 
				:key="letter"
				:class="{ active: currentLetter === letter }"
				:data-letter="letter"
			>
				{{ letter }}
			</view>
		</view>
	</view>
</template>

<script>
import $api from '../../api/home.js';

export default {
	data() {
		return {
			statusBarHeight: 0,
			currentCity: '北京', // 当前位置
			frequentCities: [], // 常用城市
			cityGroups: {}, // 按字母分组的城市
			letterList: [], // 字母列表
			currentLetter: '', // 当前字母
			scrollIntoView: '', // 滚动到指定位置
			searchKeyword: '', // 搜索关键词
			searchResult: [], // 搜索结果
			showSearchResult: false, // 是否显示搜索结果
			searchFocus: false, // 搜索框是否聚焦
			touchStartY: 0, // 触摸开始Y坐标
			letterIndexTop: 0, // 字母索引顶部位置
		}
	},
	onLoad() {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 0;
		
		// 获取当前位置
		this.getCurrentCity();
		
		// 加载城市列表
		this.loadCities();
		
		// 加载常用城市
		this.loadFrequentCities();
	},
	methods: {
		// 获取当前位置
		getCurrentCity() {
			// 从存储中获取当前城市
			const savedCity = uni.getStorageSync('currentCity');
			if (savedCity) {
				this.currentCity = savedCity;
			} else {
				// 尝试自动定位
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						// 这里可以根据经纬度反查城市，简化处理使用默认值
						this.currentCity = '北京';
					},
					fail: () => {
						this.currentCity = '北京';
					}
				});
			}
		},
		
		// 加载城市列表
		async loadCities() {
			try {
				const res = await $api.getCityList();
				if (res.data && res.data.code === 200) {
					this.cityGroups = res.data.data || {};
					// 生成字母列表
					this.letterList = Object.keys(this.cityGroups).sort();
					
					// 获取字母索引位置
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.letter-index').boundingClientRect((rect) => {
							if (rect) {
								this.letterIndexTop = rect.top;
							}
						}).exec();
					});
				} else {
					uni.showToast({
						title: res.data?.message || '加载城市列表失败',
						icon: 'none'
					});
				}
			} catch (err) {
				console.error('加载城市列表失败', err);
				uni.showToast({
					title: '加载城市列表失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 加载常用城市
		async loadFrequentCities() {
			try {
				const res = await $api.getFrequentCities();
				if (res.data && res.data.code === 200) {
					this.frequentCities = res.data.data || [];
				}
			} catch (err) {
				console.error('加载常用城市失败', err);
			}
		},
		
		// 搜索输入
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;
			if (this.searchKeyword.trim()) {
				this.searchCities();
			} else {
				this.showSearchResult = false;
				this.searchResult = [];
			}
		},
		
		// 搜索确认
		onSearchConfirm() {
			if (this.searchKeyword.trim()) {
				this.searchCities();
			}
		},
		
		// 搜索城市
		async searchCities() {
			if (!this.searchKeyword.trim()) {
				this.showSearchResult = false;
				this.searchResult = [];
				return;
			}
			
			try {
				const res = await $api.searchCities({ keyword: this.searchKeyword });
				if (res.data && res.data.code === 200) {
					this.searchResult = res.data.data || [];
					this.showSearchResult = true;
				} else {
					uni.showToast({
						title: res.data?.message || '搜索失败',
						icon: 'none'
					});
				}
			} catch (err) {
				console.error('搜索城市失败', err);
				uni.showToast({
					title: '搜索失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 选择城市
		selectCity(cityName) {
			// 保存选中的城市
			uni.setStorageSync('currentCity', cityName);
			
			// 触发城市选择事件
			uni.$emit('citySelected', cityName);
			
			// 返回上一页
			uni.navigateBack({
				delta: 1
			});
		},
		
		// 返回
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		
		// 字母索引触摸开始
		onLetterIndexTouchStart(e) {
			const touch = e.touches[0];
			this.touchStartY = touch.clientY;
			const letter = this.getLetterFromTouch(touch);
			if (letter) {
				this.currentLetter = letter;
				this.scrollToLetter(letter);
			}
		},
		
		// 字母索引触摸移动
		onLetterIndexTouchMove(e) {
			const touch = e.touches[0];
			const letter = this.getLetterFromTouch(touch);
			if (letter && letter !== this.currentLetter) {
				this.currentLetter = letter;
				this.scrollToLetter(letter);
			}
		},
		
		// 字母索引触摸结束
		onLetterIndexTouchEnd() {
			setTimeout(() => {
				this.currentLetter = '';
			}, 500);
		},
		
		// 根据触摸位置获取字母
		getLetterFromTouch(touch) {
			// 简化处理：根据触摸位置计算字母索引
			// 假设每个字母项高度约为 30rpx (约15px)
			const itemHeight = 15; // 像素
			const startY = this.letterIndexTop || 0;
			const relativeY = touch.clientY - startY;
			const index = Math.floor(relativeY / itemHeight);
			
			if (index >= 0 && index < this.letterList.length) {
				return this.letterList[index];
			}
			return null;
		},
		
		// 滚动到指定字母
		scrollToLetter(letter) {
			this.scrollIntoView = 'letter-' + letter;
		},
		
		// 滚动事件
		onScroll(e) {
			// 可以根据滚动位置更新当前字母
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #fff;
}

.position-container {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;
}

.status-bar {
	width: 100%;
	background-color: #fff;
}

.navbar {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.navbar-left {
		width: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}
	
	.navbar-center {
		flex: 1;
		display: flex;
		align-items: center;
		
		.search-box {
			flex: 1;
			display: flex;
			align-items: center;
			background-color: #fff;
			border: 2rpx solid #3c9cff;
			border-radius: 8rpx;
			padding: 16rpx 20rpx;
			
			.search-icon {
				margin-right: 16rpx;
			}
			
			.search-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
			}
		}
	}
	
	.navbar-right {
		margin-left: 20rpx;
		
		.search-btn {
			padding: 16rpx 32rpx;
			color: #3c9cff;
			font-size: 28rpx;
			font-weight: 500;
		}
	}
}

.content-scroll {
	flex: 1;
	height: 0;
}

.section {
	padding: 30rpx;
	
	.section-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 24rpx;
		font-weight: 500;
	}
	
	.city-tags {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		
		.city-tag {
			padding: 20rpx 0;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			font-size: 28rpx;
			color: #333;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 8rpx;
			text-align: center;
			
			&.current {
				background-color: #f5f5f5;
				color: #333;
				
				u-icon {
					color: #3c9cff;
				}
			}
		}
	}
}

.letter-section {
	margin-bottom: 30rpx;
	display: flex;
	
	.letter-title {
		width: 60rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding: 20rpx 0;
		text-align: center;
		flex-shrink: 0;
	}
	
	.city-tags {
		flex: 1;
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		padding: 0 20rpx;
		
		.city-tag {
			padding: 20rpx 0;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			font-size: 28rpx;
			color: #333;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}

.letter-index {
	position: fixed;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 10rpx 8rpx;
	z-index: 100;
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 20rpx 0 0 20rpx;
	
	.letter-item {
		font-size: 20rpx;
		color: #999;
		padding: 2rpx 4rpx;
		line-height: 1.4;
		
		&.active {
			color: #3c9cff;
			font-weight: bold;
		}
	}
}
</style>
